package dao;

import java.util.ArrayList;

import modelo.Fornecedor;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class DaoFornecedor {
	private SessionFactory fabrica;

	public DaoFornecedor()throws Exception
	{	fabrica=new Configuration().addClass(modelo.Fornecedor.class).buildSessionFactory();
		
	}
	public void cadastrar(Fornecedor f)throws Exception
	{
		Session sessao=fabrica.openSession();
		Transaction transacao=sessao.beginTransaction();
		sessao.save(f);
		transacao.commit();
		sessao.flush();
		sessao.close();
	}
	
	public Fornecedor consultar(Fornecedor f)throws Exception
	{
		Session sessao=fabrica.openSession();
		Transaction transacao=sessao.beginTransaction();
		f=(Fornecedor)sessao.get(modelo.Fornecedor.class,f.getId_forn());
		
		transacao.commit();
		sessao.flush();
		sessao.close();
		return f;
	}
	public void excluir(Fornecedor f)throws Exception
	{
		Session sessao=fabrica.openSession();
		Transaction transacao=sessao.beginTransaction();
		sessao.delete(f);
		transacao.commit();
		sessao.flush();
		sessao.close();
	}
	public void alterar(Fornecedor f)throws Exception
	{
		Session sessao=fabrica.openSession();
		Transaction transacao=sessao.beginTransaction();
		sessao.update(f);
		transacao.commit();
		sessao.flush();
		sessao.close();
	}
	
	public ArrayList<Fornecedor> consultarTodos(){
		Session sessao=fabrica.openSession();
		Transaction transacao=sessao.beginTransaction();
		Query q=sessao.createQuery("from modelo.Fornecedor");
		ArrayList<Fornecedor> fornecs=(ArrayList<Fornecedor>)q.list();
		transacao.commit();
		sessao.flush();
		sessao.close();
		return fornecs;
	}
	
	public ArrayList<Fornecedor> consultarTodosNome(String nome){
		Session sessao=fabrica.openSession();
		Transaction transacao=sessao.beginTransaction();
		Query q=sessao.createQuery("from modelo.Fornecedor where nome_forn like '%" + nome + "%' order by nome_forn");
		ArrayList<Fornecedor> fornecs=(ArrayList<Fornecedor>)q.list();
		transacao.commit();
		sessao.flush();
		sessao.close();
		return fornecs;
	}
	
	public ArrayList<Fornecedor> consultarAtivos(){
		Session sessao=fabrica.openSession();
		Transaction transacao=sessao.beginTransaction();
		Query q=sessao.createQuery("from modelo.Fornecedor where ativo = true");
		ArrayList<Fornecedor> fornecs=(ArrayList<Fornecedor>)q.list();
		transacao.commit();
		sessao.flush();
		sessao.close();
		return fornecs;
	}
	
	
}
